package com.flyduck.modules.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.common.lang.Result;
import com.flyduck.modules.app.controller.BaseController;
import com.flyduck.modules.system.service.SysUserService;
import com.flyduck.modules.system.vo.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * <p>
 * SysUserController
 * </p>
 *
 * @author flyduck
 * @since 2024-06-03
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseController {

    @Resource
    private SysUserService sysUserService;

    @GetMapping("/getUserPage")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result<Page<SysUserRespVO>> getUserPage(SysUserQueryReqVO sysUserQueryReqVO){
        Page<SysUserRespVO> sysUserRespVOPage = sysUserService.getUserPage(getPage(),sysUserQueryReqVO);
        return Result.success(sysUserRespVOPage);
    }

    @GetMapping("/getUserDetailsById/{id}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result<SysUserDetailsRespVO> getUserDetailsById(@PathVariable("id") Long id){
        SysUserDetailsRespVO sysUserDetailsRespVO = sysUserService.getUserDetailsById(id);
        return Result.success(sysUserDetailsRespVO);
    }

    @PostMapping("/saveUser")
    @PreAuthorize("hasAuthority('sys:user:save')")
    public Result<Void> saveUser(@Validated @RequestBody SysUserSaveReqVO sysUserSaveReqVO){
        sysUserService.saveUser(sysUserSaveReqVO);
        return Result.success();
    }

    @PostMapping("/updateUser")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result<Void> updateUser(@Validated @RequestBody SysUserUpdateReqVO sysUserUpdateReqVO){
        sysUserService.updateUser(sysUserUpdateReqVO);
        return Result.success();
    }

    @PostMapping("/batchDeleteByIds")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result<Void> batchDeleteByIds(@RequestBody Long[] ids){
        sysUserService.batchDeleteByIds(Arrays.asList(ids));
        return Result.success();
    }

    @PostMapping("/assignRolesToUser/{userId}")
    @PreAuthorize("hasAuthority('sys:user:perm')")
    public Result<Void> assignRolesToUser(@PathVariable(name = "userId")Long userId,@RequestBody Long[] roleIds){
        sysUserService.assignRolesToUser(userId,Arrays.asList(roleIds));
        return Result.success();
    }

    @PostMapping("/resetPasswordById/{id}")
    @PreAuthorize("hasAuthority('sys:user:resetPwd')")
    public Result<Void> resetPasswordById(@PathVariable("id") Long id){
        sysUserService.resetPasswordById(id);
        return Result.success();
    }

}
